<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;

/**
 * 馆藏推荐书籍表
 * Class LibBookBarcodeModel
 * @package app\common\model
 */
class LibBookType extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'lib_book_type';


    /*关联活动申请*/
    public function conBookInfo()
    {
        return $this->hasMany(LibBookRecom::class, 'type_id', 'id');
    }

    /**
     * 获取列表
     * @param token ：用户 token
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function getRecomBookType($limit = 10)
    {
        $res = $this->select('id', 'type_name', 'create_time')
            ->with(['conBookInfo' => function ($query) {
                $query->select('id', 'metaid', 'metatable', 'type_id', 'book_name', 'author', 'press', 'pre_time', 'isbn', 'price', 'img', 'intro')->limit(9);
            }])
            ->whereHas('conBookInfo', function ($query) {
                $query->where('is_del', 1);
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->limit($limit)
            ->get()
            ->toArray();

        return $res;
    }


    /**
     * 判断类型是否存在，如果存在则直接返回类型id，不存在则添加
     * @param type_name 类型名
     */
    public function getTypeId($type_name)
    {
        if (empty($type_name)) {
            return '参数错误';
        }
        $res = $this->where('type_name', $type_name)->first();
        if ($res) {
            return $res->id;
        }
        $this->type_name = $type_name;
        $this->save();
        return $this->id;
    }
}
